package com.niodata.dp.monitor.common.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.niodata.dp.monitor.common.entity.Message;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import okhttp3.ConnectionPool;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.log4j.Logger;

public class DingDingMsgUtil {

  private static final Logger logger = Logger.getLogger(DingDingMsgUtil.class);
  private static OkHttpClient client;
  private static ExecutorService executorService = Executors.newCachedThreadPool();

  static {
    ConnectionPool pool = new ConnectionPool(10, 30, TimeUnit.SECONDS);
    OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder()
          .connectTimeout(15, TimeUnit.SECONDS)
          .readTimeout(120L, TimeUnit.SECONDS)
          .writeTimeout(120L, TimeUnit.SECONDS)
          .retryOnConnectionFailure(true)
          .connectionPool(pool);
    client = httpClientBuilder.build();
  }

  /**
   * send dingding msg.
   */
  public static void sendDingDingMsg(final String dingdingUrl, final String msg)
        throws IOException {
    String contentType = "application/json; charset=utf-8";
    MediaType jsonMediaType = MediaType.parse(contentType);
    RequestBody requestBody = RequestBody.create(jsonMediaType, msg);
    Request request = new Request.Builder()
          .header("Content-Type", contentType)
          .url(dingdingUrl)
          .post(requestBody)
          .build();
    Response response = null;
    try {
      response = client.newCall(request).execute();
      if (!response.isSuccessful() || (response.body() != null && response.body().string()
            .toLowerCase().contains("errcode"))) {
        String error = "";
        if (response.body() != null) {
          error = response.body().string();
          logger.error("msg send error" + error);
          System.out.println("msg send error" + error);
        }
      } else {

        logger.info(String.format("Send DingDing msg:  %s success!", msg));
      }
    } catch (Exception e) {
      logger.error("ding msg send error!", e);
      System.out.println("ding msg send error!" + e);
    } finally {
      if (response != null) {
        response.close();
      }
    }

  }

  public static String buildDingDingMsg(Message message)
        throws IOException, TemplateException {
    String messageStr = "";
    String templateKey = "TASK_DINGDING";
    Map<Object, Object> messageMap = new HashMap<>();
    if (message != null) {
      ObjectMapper mapper = new ObjectMapper();
      messageMap = mapper.convertValue(message, Map.class);
    }
    messageStr = TemplateUtil.genMsgByTemplate(templateKey, messageMap);
    return messageStr;
  }

  public static String buildDingDingMsgByTemplateKey(String templateKey, Message message)
        throws IOException, TemplateException {
    String messageStr = "";
    Map<Object, Object> messageMap = new HashMap<>();
    if (message != null) {
      ObjectMapper mapper = new ObjectMapper();
      messageMap = mapper.convertValue(message, Map.class);
    }
    messageStr = TemplateUtil.genMsgByTemplate(templateKey, messageMap);
    return messageStr;
  }

}
